package com.example.starter.mybatis.injector.method;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.example.starter.mybatis.anntation.DeleteTime;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author 王令
 * @since 2022/7/22 11:53
 */
public abstract class ExampleAbstractMethod extends AbstractMethod {

    @Override
    protected String sqlLogicSet(TableInfo table) {
        StringBuilder sqlLogicSet = new StringBuilder(super.sqlLogicSet(table));
        List<Field> allFields = TableInfoHelper.getAllFields(table.getEntityType());
        for (Field field : allFields) {
            final DeleteTime deleteTime = field.getAnnotation(DeleteTime.class);
            if (deleteTime != null) {
                TableFieldInfo deleteTimeField =
                        table.getFieldList().stream().filter(info -> field.getName().equals(info.getProperty()))
                                .findFirst().orElseThrow(() ->
                                        ExceptionUtils.mpe(
                                                "can't find the @DeleteTime filed from table {%s}",
                                                table.getTableName()
                                        )
                                );
                sqlLogicSet.append(", ").append(deleteTimeField.getColumn()).append("=now()");
            }
        }
        return sqlLogicSet.toString();
    }

}
